package com.ddone.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ddone.mapper.SysRoleMapper;
import com.ddone.mapper.SysUserRoleMapper;
import com.ddone.model.auth.SysRole;
import com.ddone.model.auth.SysUserRole;
import com.ddone.model.vo.AssignRoleVo;
import com.ddone.model.vo.SysRoleQueryVo;
import com.ddone.service.SysRoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author ddone
 * @date 2024/3/26-23:54
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Override
    public Page<SysRole> queryPage(Page<SysRole> rolePage, SysRoleQueryVo roleQueryVo) {
        return sysRoleMapper.queryPage(rolePage, roleQueryVo);
    }

    @Override
    public Map<String, Object> getRolesByUserId(String userId) {
        // 获取所有角色
        List<SysRole> sysRoles = sysRoleMapper.selectList(null);

        // 获取用户角色记录
        LambdaQueryWrapper<SysUserRole> userRoleWrapper = new LambdaQueryWrapper<>();
        userRoleWrapper.eq(SysUserRole::getUserId, userId);
        List<SysUserRole> userRoleList = sysUserRoleMapper.selectList(userRoleWrapper);

        // 封装用户的角色ID列表
        List<Long> userRoleIds = new ArrayList<>();
        userRoleList.forEach(item -> userRoleIds.add(item.getRoleId()));
        HashMap<String, Object> resultMap = new HashMap<>();

        // 封装对象返回
        resultMap.put("userRoleIds", userRoleIds);
        resultMap.put("allRoles", sysRoles);

        return resultMap;
    }

    @Override
    public void doAssign(AssignRoleVo assignRoleVo) {

        Long userId = assignRoleVo.getUserId();

        // 根据用户id删除原来分配的角色
        LambdaQueryWrapper<SysUserRole> deleteWrapper = new LambdaQueryWrapper<>();
        deleteWrapper.eq(SysUserRole::getUserId, assignRoleVo.getUserId());
        sysUserRoleMapper.delete(deleteWrapper);

        // 获取所有的角色id 变成userRole 列表
        List<SysUserRole> sysUserRoleRecords = assignRoleVo.getRoleIdList()
                .stream()
                .filter(Objects::nonNull)
                .map(roleId -> {
                    SysUserRole sysUserRole = new SysUserRole();
                    sysUserRole.setUserId(userId);
                    sysUserRole.setRoleId(roleId);
                    return sysUserRole;
                })
                .collect(Collectors.toList());
        sysUserRoleMapper.batchInsert(sysUserRoleRecords);
    }

}
